<template>
  <div class="app-container">
    <el-form
      ref="imageInfoForm"
      :model="imageInfo"
      label-width="120px"
      class="form-container"
      :rules="imageInfoRules"
    >
      <el-form-item label="图片标题" prop="title">
        <el-input v-model="imageInfo.title" />
      </el-form-item>
      <el-form-item label="图片描述" prop="description">
        <el-input v-model="imageInfo.description" />
      </el-form-item>
      <el-form-item label="图片标签" prop="label">
        <el-input v-model="imageInfo.label" />
      </el-form-item>
      <el-form-item label="图片链接" prop="url" hidden>
        <el-input v-model="imageInfo.url" />
      </el-form-item>
      <el-form-item label="上传图片">
        <el-upload
          ref="upload"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :multiple="false"
          action=""
          :limit="1"
          list-type="picture"
          :http-request="customUploadImage"
        >
          <el-button slot="trigger" size="small" type="primary"
            >上传图片</el-button
          >
          <div slot="tip" class="el-upload__tip">
            选择上传的图片之后会自动上传
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmitImage">提交</el-button>
        <el-button @click="handleCancelImage">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { insertImage, fetchOssTokenApi } from "@/api/image";
import { mapState } from "vuex";
import OSS from "ali-oss";

export default {
  data() {
    return {
      imageInfo: {
        url: "",
        title: "",
        description: "",
        label: "",
      },
      imageInfoRules: {
        url: [
          { required: true, message: "是不是忘了上传图片？", trigger: "blur" },
        ],
        title: [{ required: true, message: "请输入图片标题", trigger: "blur" }],
        description: [
          { required: true, message: "请输入图片描述", trigger: "blur" },
        ],
        label: [{ required: true, message: "请输入图片标签", trigger: "blur" }],
      },
    };
  },
  computed: {
    ...mapState({
      token: (state) => state.user.token,
    }),
  },
  methods: {
    handleSubmitImage() {
      this.$refs["imageInfoForm"].validate((valid) => {
        if (valid) {
          insertImage(this.imageInfo).then((res) => {
            this.$notify.success({
              title: "提示",
              message: res.message,
            });
            setTimeout(() => {
              this.$router.push("/image/images");
            }, 1000);
          });
        } else {
          this.$message.warning({
            message: "请完整填写信息",
            showClose: true,
          });
        }
      });
    },
    handleCancelImage() {
      this.imageInfo = {
        url: "",
        title: "",
        description: "",
        label: "",
      };
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    customUploadImage(e) {
      fetchOssTokenApi().then((res) => {
        const tokenInfo = res.data;
        let client = new OSS({
          region: tokenInfo.region,
          accessKeyId: tokenInfo.accessKeyId,
          accessKeySecret: tokenInfo.accessKeySecret,
          stsToken: tokenInfo.securityToken,
          bucket: tokenInfo.bucket,
        });
        //上传文件
        const fp = e.file;
        // 构造文件名
        const name = fp.name;
        const fileType = fp.type; //获取文件类型
        const isImage = fileType.indexOf("image") != -1; // 判断是否是图片类型
        if (!isImage) {
          this.$notify.error({
            title: "提示",
            message: "请选择图片类型文件",
          });
          this.$refs.upload.uploadFiles = [];
          return;
        }
        let strs = name.split(".");
        const filename = tokenInfo.uuid + "." + strs[strs.length - 1];
        let curTime = new Date();
        let year = curTime.getFullYear(),
          month = curTime.getMonth() + 1,
          day = curTime.getDate();
        let dir =
          year +
          "/" +
          (month < 10 ? "0" + month : month) +
          "/" +
          (day < 10 ? "0" + day : day) +
          "/";
        client
          .put(dir + filename, fp)
          .then((res) => {
            this.imageInfo.url = res.url;
            this.$notify.success({
              title: "提示",
              message: "图片上传成功",
            });
          })
          .catch((err) => {
            this.$notify.error({
              title: "提示",
              message: "出现未知错误，图片上传失败",
            });
          });
      });
    },
  },
};
</script>

<style scoped>
.form-container {
  width: 80%;
}
</style>
